package miku.firstgame.net.proxy
{

	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;

	import miku.firstgame.net.IConnection;
	import miku.firstgame.net.IConnectionHandler;
	import miku.firstgame.net.pack.IReceivePack;

	import org.puremvc.as3.patterns.proxy.Proxy;

	/**
	 * 处理注册协议
	 * @author kant
	 * @date 2010-01-06
	 */
	//TODO TODOID201004020001 ConnectionProxy 重构时需要仔细考虑，最初写ConnectionProxy的时候，没有考虑到负载均衡的情况
	//应该是一个Connection对应一个ConnectionHandler
	public class Connection implements IConnectionHandler
	{
		/**
		 * 此NAME的值不能改,会影响到express
		 * 必须与express项目express.chat.utils.constant.ProxyNameConstant.as中的ConnectionProxy值一样
		 */

		private static var instance:Connection;

		private var handlerMap:Object;
		private var handlerIndex:Dictionary;

		//private var cometTimeoutTimer:int;

		public function Connection()
		{
			super();

			handlerMap = {};
			handlerIndex = new Dictionary();

//			registerProtocolInterest(handleD, ["d"]);
//			registerProtocolInterest(handleDS, ["DS"]);
//			registerProtocolInterest(handleAnnouncement, ["Announcement"]);
//			registerProtocolInterest(handleInitRoomList, ["InitRoomList"]);
//			registerProtocolInterest(onRRMIFProtocol, ["RRMIF"]);
//			registerProtocolInterest(onChangeUserProfileProtocol, ["EUP"]);
//			registerProtocolInterest(onChangedRoom, ["ChangedRoom"]);
			instance = this;
		}

		public static function getInstance():Connection
		{
			return instance;
		}

		//TODO TODOID201004020001
		public function handleConnect(connection:IConnection):void
		{
			trace("[Connection Success]");
			//sendNotification("ApplicationConstants/connectionClosed", true);
			//TODO
			//TEST
			//DS
			//TODO 不知道这段代码干什么用的
			//var connMgr:ConnectionManager = ConnectionManager.getInstance();
			//if ( connMgr.getDSMode() )
			//{
			//	Logger.warn("[DS] starting....");
			//	var managerProxy:ManagerProxy = ManagerProxy(facade.retrieveProxy(ManagerProxy.NAME));
			//	var ds:DispatchServerVO = connMgr.getDS();
			//	connMgr.registerConnection( ds.roomId, ds.socketVO );
			//	facade.registerProxy( new DSProxy(ds.roomId) );
			//	managerProxy.doInitRequest();
			//	return;
			//}

			//这里的Connection有可能是来自广告的Connection，目前这类Connection没有被ConnectionManager管理，所以也不能触发状态机
//			var connectionGroup:ConnectionGroup = getConnectionGroupByConnection(connection);
//			if (connectionGroup)
//			{
//				var managerProxy:ManagerProxy = ManagerProxy(facade.retrieveProxy(ManagerProxy.NAME));
//				managerProxy.doInitRequest(connectionGroup.currentActiveConnection);
//				return;
//			}
//			var theSameConnection:Boolean;
//			if (connection == connectionManager.masterConnection)
//			{
//				theSameConnection = true;
//			}
//			if (connectionManager.masterConnection is WrappedSock &&
//				(connectionManager.masterConnection as WrappedSock).instance == connection)
//			{
//				theSameConnection = true;
//			}
//			if (theSameConnection)
//			{
//				var context:AppManagerContext = AppManagerContext.getInstance();
//				context.forcedOut = false;
//				context.overConnected = false;
//				sendNotification(StateMachine.ACTION, null, ActionConstants.ACTION_INITIALIZE_SESSION);
//			}
		}

		//TODO TODOID201004020001
		public function handleClose(connection:IConnection):void
		{
			trace("[Connection Closed]");
			//WrappedSock.isLoadInitProtocol = false;

		}

		//TODO TODOID201004020001
		public function handleError(connection:IConnection):void
		{
			trace("[Connection Error]");

		}

		public function registerProtocolInterest(handler:Function, interest:Array):void
		{
			var arg:Object;
			for (var i:int = 0; i < interest.length; i++)
			{
				arg = interest[i];
				if (handlerMap[arg] == null)
				{
					handlerMap[arg] = [];
				}
				handlerMap[arg] = handlerMap[arg].concat([handler]);
			}
			if (handlerIndex[handler] == null)
			{
				handlerIndex[handler] = [];
			}
			handlerIndex[handler] = handlerIndex[handler].concat(interest);
			trace("Registed Protocal:" + handlerIndex[handler]);
		}

		public function unregisterHandler(handler:Function):void
		{
			var interests:Array = handlerIndex[handler];
			for each (var name:String in interests)
			{
				handlerMap[name].splice(handlerMap[name].indexOf(handler), 1);
			}
		}

		//TODO TODOID201004020001
		public function handleData(data:IReceivePack, connection:IConnection):void
		{

			var handlerSet:Object = handlerMap[data.tag];

			//TODO TODOID201004210003 协议及普通数据的处理应该可以分的更开些
			for each (var handler:Function in handlerSet)
			{
				handler.call(null, data, connection);
			}
		}

	}
}
